package com.netease.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.SegToken;
import com.netease.mapper.StandardFieldInfoMapper;
import com.netease.mapper.YouDaoTranslationMapper;
import com.netease.pojo.StandardFieldInfo;
import com.netease.service.RootInfoService;
import com.netease.service.StandFieldService;
import com.netease.service.WordSegmentLogService;
import com.netease.entity.DataElementTable;
import com.netease.entity.Word;
import com.netease.pojo.RootInfo;
import com.netease.utils.*;
import org.n3r.idworker.Sid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据元素生成服务impl
 *
 * @author aochong
 * @date 2022/12/19
 */
@Service
public class StandFieldServiceImpl implements StandFieldService {
    private static final Logger logger = LoggerFactory.getLogger(FileLoadUtils.class);
    private static final String PATH1 = "oa_root.csv";
    @Autowired
    private RootInfoService rootInfoService;
    @Autowired
    private WordSegmentLogService wordSegmentLogService;
    @Autowired
    private Sid sid;
    @Autowired
    private StandardFieldInfoMapper standFieldMapper;

    public StandFieldServiceImpl() {}

    /**
     * 构建数据元素
     *
     * @param text 文本
     * @return {@link String}
     */
    @Override
    public ArrayList<Word> builderStandField(String text, JiebaSegmenter segmenter) {

        ArrayList<Word> arrayList = new ArrayList<>();

        //分词
        List<SegToken> splitWord = segmenter.process(text.replaceAll("-","").replaceAll("停","").replaceAll("P","").replaceAll("_",""), JiebaSegmenter.SegMode.SEARCH);

        for (int i = 0; i < splitWord.size(); i++) {
            Word word = new Word();
            word.setInitialName(text);
            word.setName(splitWord.get(i).word);
            word.setStartOffset(splitWord.get(i).startOffset);
            word.setEndOffset(splitWord.get(i).endOffset);
            //查询当前词根是否存在
            if (rootInfoService.queryRootIsExist(word)){
                RootInfo rootInfo = rootInfoService.queryRoot(word);
                //词频+1
                rootInfo.setWordFrequency(rootInfo.getWordFrequency()+1);
                //设置更新时间
                rootInfo.setUpdateTime(DateUtil.dateToString(new Date()));
                word.setEngName(rootInfo.getTranslt());
                word.setEngAbbreviation(rootInfo.getRootNm());
                //词频+1
                word.setWordFrequency(rootInfo.getWordFrequency());
                //更新数据
                rootInfoService.updateRoot(rootInfo);
                logger.info("Date()：" + DateUtil.dateToString(new Date()));
                //插入分词日志至MySQL数据库
                wordSegmentLogService.createWordSegmentLog(word);

                arrayList.add(word);
            }else{
                try {
                    //调用翻译接口进行中文翻译
                    JSONObject jsonObject = JSONObject.parseObject(YouDaoTranslationMapper.translation(splitWord.get(i).word));
                    if (jsonObject.getJSONArray("translation") != null){
                        StringBuilder sb = new StringBuilder();
                        sb.append(jsonObject.getJSONArray("translation") == null ? "":jsonObject.getJSONArray("translation").get(0).toString().toLowerCase());
                        if (jsonObject.getJSONObject("basic") != null){
                            JSONArray jsonArray = jsonObject.getJSONObject("basic").getJSONArray("explains");
                            StringUtils.jsonArray2String(jsonArray,sb);
                        }
                        String wordStr = sb.toString();
                        word.setEngName(wordStr);
                        //设置英文缩写
                        word.setEngAbbreviation(StringUtils.removeVowels(wordStr));
                        //对单词进行排序
//                    word.engAbbreviationSort();
                        word.setEngAbbreviation(word.getEngAbbreviation().split("\\|")[0].replaceAll(" ","_"));
                        //设置词频
                        word.setWordFrequency(1);
                    }
                    arrayList.add(word);

                    //将新增词根写入MySQL数据库
                    rootInfoService.createRoot(word);
                    //插入分词日志至MySQL数据库
                    wordSegmentLogService.createWordSegmentLog(word);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        try {
            StandardFieldInfo standardFieldInfo = new StandardFieldInfo();
            standardFieldInfo.setId(sid.nextShort());
            standardFieldInfo.setChnsName(arrayList.get(0).getInitialName());
            StringBuilder sb = new StringBuilder();
            //遍历
            for (int i = 0; i < arrayList.size(); i++) {
                sb.append(arrayList.get(i).getEngAbbreviation());
                if (i < arrayList.size()-1){
                    sb.append("_");
                }
            }
            standardFieldInfo.setEngName(sb.toString());
            standardFieldInfo.setCreatedTime(DateUtil.dateToString(new Date()));
            standardFieldInfo.setUpdatedTime(DateUtil.dateToString(new Date()));

            if (!queryStandFieldIsExists(standardFieldInfo)) {
                //向数据库插入标准字段
                insertStandField(standardFieldInfo);
            }
        }catch (Exception e) {
            logger.error(text + "" + arrayList.stream().map(Object::toString).collect(Collectors.joining(", ")));
            e.printStackTrace();
        }

        return arrayList;
    }

    @Override
    public List<DataElementTable> segmentWordTranslation(DataElementTable dataElementTable, JiebaSegmenter segmenter) {

        ArrayList<DataElementTable> arrayList = new ArrayList<>();
        ArrayList<Word> list1 = new ArrayList<>();

        //中文分词
        List<SegToken> splitWord = segmenter.process(dataElementTable.getFieldName(), JiebaSegmenter.SegMode.SEARCH);

        for (int i = 0; i < splitWord.size(); i++) {
            StringBuilder sb = new StringBuilder();
            Word word = new Word();
            word.setInitialName(dataElementTable.getFieldName());
            word.setName(splitWord.get(i).word);
            word.setStartOffset(splitWord.get(i).startOffset);
            word.setEndOffset(splitWord.get(i).endOffset);

            translation(splitWord.get(i).word,word);
            list1.add(word);

            sb.append(dataElementTable.getTableName() + "," + dataElementTable.getFieldName() + "," + word.getName() + "," + word.getEngName() + "," + word.getEngAbbreviation());
            CsvUtils.exportCsv(new File(PATH1), sb.toString());
        }

        dataElementTable.setWords(list1);
        arrayList.add(dataElementTable);

        return arrayList;
    }

    @Override
    public void insertStandField(StandardFieldInfo standardFieldInfo) {
        standFieldMapper.insert(standardFieldInfo);
    }

    @Override
    public boolean queryStandFieldIsExists(StandardFieldInfo standardFieldInfo) {
        Example example = new Example(StandardFieldInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("chnsName",standardFieldInfo.getChnsName());

        return standFieldMapper.selectOneByExample(example) != null;
    }

    public void translation(String wordStr, Word word){
        //调用翻译接口进行中文翻译
        JSONObject jsonObject = JSONObject.parseObject(YouDaoTranslationMapper.translation(wordStr));
        if (jsonObject.getJSONArray("translation") != null){
            StringBuilder sb = new StringBuilder();
            sb.append(jsonObject.getJSONArray("translation") == null ? "":jsonObject.getJSONArray("translation").get(0).toString().toLowerCase());
            if (jsonObject.getJSONObject("basic") != null){
                JSONArray jsonArray = jsonObject.getJSONObject("basic").getJSONArray("explains");
                StringUtils.jsonArray2String(jsonArray,sb);
            }
            String wordStr1 = sb.toString();
            word.setEngName(wordStr1);
            word.setEngAbbreviation(StringUtils.removeVowels(wordStr1));
//              word.engAbbreviationSort();
            word.setEngAbbreviation(word.getEngAbbreviation().split("\\|")[0].replaceAll(" ","_"));
        }
    }
}
